package utils;

import constants.CommonConstants;
import constants.DeployMode;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class DBCPUtils {
    private static DataSource datasource;
    private static Properties properties;

    //初始化配置
    static {
        properties = new Properties();
        DeployMode deployMode = PropertiesManagerUtil.mode;
        String resourceName = deployMode.toString().toLowerCase() + File.separator + CommonConstants.DBCP_COMMON_FILE_NAME;

        try {
            properties.load(DBCPUtils.class.getClassLoader().getResourceAsStream(resourceName));
            datasource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化连接池
    public static DataSource getDataSource() {
        return datasource;
    }

    public static Connection getConnection() {
        try {
            return datasource.getConnection();
        } catch (SQLException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

}

